package com.it.myd.controller.main;

import com.it.myd.bean.main.File;
import com.it.myd.bean.main.ReturnValue;
import com.it.myd.bean.main.User;
import com.it.myd.service.main.LoginService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.List;

@Controller
@RequestMapping("/signup")
public class SignupController {

    @Autowired
    private LoginService loginService;

    @RequestMapping("check")
    @ResponseBody
    public ReturnValue check(Model model,HttpServletRequest request) {
        ReturnValue<String> ret = new ReturnValue<>();
        String yhm = request.getParameter("yhm");
        List<User> list = loginService.CheckUsername(yhm);
        if(list.size() > 0){
            ret.setRetDesc("用户名已被使用!");
            ret.setRetCode("9999");
        }else{
            ret.setRetDesc("可以使用");
            ret.setRetCode("0000");
        }
        return ret;
    }

    @RequestMapping("signup")
    public String signup(Model model,@ModelAttribute User user_z,HttpServletRequest request) {
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user_z.setUser_status_time(sdf.format(System.currentTimeMillis()));
        loginService.SignUser(user_z);
        User user = loginService.CheckUser(user_z);
        user_z.setUser_id(user.getUser_id());
        user_z.setUser_status("20001");
        loginService.insertUserStatus(user_z);

        //设置初始头像地址 以防后续通过头像查不到数据
        File userimg = new File();
        userimg.setFile_name("undefined.jpg");
        userimg.setFile_path("/userimg/");
        user.setUser_img(userimg);
        loginService.insertUserProFile(user);

        request.setAttribute("user_name",user_z.getUser_name());
        request.setAttribute("user_pw",user_z.getUser_pw());
        ReturnValue<String> ret = new ReturnValue<>();
        ret.isSuccess("注册成功!");
        model.addAttribute("ret",ret);
        return "main/login";
    }

}
